package com.class3.team.fossilProject.serviceImpl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.class3.team.fossilProject.entity.Book;
import com.class3.team.fossilProject.repository.BookRepository;
import com.class3.team.fossilProject.service.BookService;@Service
@Transactional
public class BookServiceImpl implements BookService{
    
    @Autowired
    public BookRepository bookR;
    
	@Override
	public JSONObject getBookById(Integer bookId) {
		// TODO Auto-generated method stub
		Book book = bookR.findByBookId(bookId);
		JSONObject jo = new JSONObject(true);
		jo.put("type", "Feature");
		// 创建 properties的json对象
		JSONObject p = new JSONObject(true);
		p.put("phylum", book.getPhylum());
		p.put("class", book.getClassName());
		p.put("order", book.getOrderName());
		p.put("family", book.getFamily());
		p.put("genus", book.getGenus());
		p.put("species", book.getSpecies());
		p.put("start_year", book.getStartYear());
		p.put("end_year", book.getEndYear());
		jo.put("properties", p);
		JSONObject geo = new JSONObject(true);
		geo.put("type", "Point");
		// 创建点对应的对象
		String[] location = new  String[2];
		location[0] = book.getModernLongitude();
		location[1] = book.getModernLatitude();
		geo.put("coordinates", location);

		jo.put("geometry", geo);
        return jo;
	}

	@Override
	public JSONArray getJAByEleName(String name) {
		JSONArray res = new JSONArray();
		List<Book> list = bookR.findAll();
		for(Book k : list) {
			Set<String> set = handleBook(k);
			if(set.contains(name)) {
				res.add(getBookById(k.getBookId()));
			}
		}
		return res;
	}
	
	
	private Set<String> handleBook(Book k){
		Set<String> set = new HashSet<String>();
		set.add(k.getPhylum());
		
		if(k.getClassName().length() == 0)
			set.add("NoClass");
		else 
			set.add(k.getClassName());
		
		if(k.getOrderName().length() == 0)
			set.add("NoOrder");
		else
			set.add(k.getOrderName());
		
		if(k.getFamily().length() == 0)
			set.add("NoFamily");
		else
			set.add(k.getFamily());
		
		set.add(k.getGenus());
		set.add(k.getSpecies());
		return set;
	}

}






